package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService detailService;

    @Autowired
    PurchaseService purchaseService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        LambdaQueryWrapper<PurchaseEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.PURCHASE_STATUS_NEW.getCode())
                .or()
                .eq(PurchaseEntity::getStatus, WareConstant.PurchaseStatusEnum.PURCHASE_STATUS_ASSIGNED.getCode());
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }


    @Transactional
    @Override
    public R mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        List<Long> items = mergeVo.getItems();
        List<PurchaseDetailEntity> listByIds = detailService.listByIds(items);
        List<Object> collect = listByIds.stream().filter(item -> {
            // 当采购单的状态是0或1时才可以合并
            if (item.getStatus() == WareConstant.PurchaseStstusDeailEnum.PURCHASE_STATUS_NEW.getCode() || item.getStatus() == WareConstant.PurchaseStstusDeailEnum.PURCHASE_STATUS_ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        if (collect.size() > 0) {
            // 若 purchaseId 为null则新建采购单，否则合并
            if (purchaseId == null) {
                PurchaseEntity purchaseEntity = new PurchaseEntity();
                purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.PURCHASE_STATUS_NEW.getCode());
                // 当purchaseId为null新建采购单时修改原采购单的采购人和状态
                purchaseService.updateOrginalPurchase(items);
                this.save(purchaseEntity);
                purchaseId = purchaseEntity.getId(); // 将保存之后得到的id赋值给purchaseId以便更新PurchaseDetailEntity
            }
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> detailEntities = items.stream().map(i -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(i);
                detailEntity.setPurchaseId(finalPurchaseId);
                // TODO 这里有争议，并不是合并之后就一定是已分配的状态，如果没有分配直接修改为已分配不太合理
                detailEntity.setStatus(WareConstant.PurchaseStstusDeailEnum.PURCHASE_STATUS_ASSIGNED.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            detailService.updateBatchById(detailEntities);
            return R.ok("合并成功!");
        }
        return R.error(1,"非新建和已分配的采购单无法合并!");
    }
    @Override
    public void updateOrginalPurchase(List<Long> items) {
        List<PurchaseEntity> purchaseEntities = items.stream().map(item -> {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(item);
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.PURCHASE_STATUS_NEW.getCode());
            return purchaseEntity;
        }).collect(Collectors.toList());
        this.updateBatchById(purchaseEntities);
    }



    @Transactional
    @Override
    public void received(List<Long> ids) {
        // 1、 确认当前采购单是新建或已分配状态
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(purchase -> {
            return purchase.getStatus() == WareConstant.PurchaseStstusDeailEnum.PURCHASE_STATUS_NEW.getCode() || purchase.getStatus() == WareConstant.PurchaseStstusDeailEnum.PURCHASE_STATUS_ASSIGNED.getCode();
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.PURCHASE_STATUS_RECEIVED.getCode());
            return item;
        }).collect(Collectors.toList());
        // 2、改变采购单的状态
        this.updateBatchById(purchaseEntities);
        // 3、改变采购项的状态
        purchaseEntities.forEach(purchaseEntity -> {
            List<PurchaseDetailEntity> entities = detailService.listDetailByPurchaseId(purchaseEntity.getId());
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(purchaseDetailEntity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(purchaseDetailEntity.getId());
                detailEntity.setStatus(WareConstant.PurchaseStstusDeailEnum.PURCHASE_STATUS_BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            detailService.updateBatchById(detailEntities);
        });
    }


    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {

        Long id = doneVo.getId();
        //2、改变采购项状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();

        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseStstusDeailEnum.PURCHASE_STATUS_FAILED.getCode()){
                flag = false;
                detailEntity.setStatus(item.getStatus());
            }else {
                detailEntity.setStatus(WareConstant.PurchaseStstusDeailEnum.PURCHASE_STATUS_FINISHED.getCode());
                //3、将成功采购的进行入库
                //先查出商品的PurchaseDetailEntity表中的sku_id
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        detailService.updateBatchById(updates);
        //1、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.PURCHASE_STATUS_FINISHED.getCode() : WareConstant.PurchaseStatusEnum.PURCHASE_STATUS_HASERROR.getCode());
        this.updateById(purchaseEntity);

    }

}